#!/bin/bash

# FluvioX开发环境启动脚本

set -e

echo "🚀 启动FluvioX开发环境..."

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    echo "❌ Docker未运行，请先启动Docker"
    exit 1
fi

# 检查Fluvio CLI是否安装
if ! command -v fluvio &> /dev/null; then
    echo "📦 安装Fluvio CLI..."
    curl -fsS https://hub.infinyon.cloud/install/install.sh | bash
    export PATH="$HOME/.fluvio/bin:$PATH"
fi

# 启动基础服务
echo "🐘 启动PostgreSQL和Redis..."
docker-compose up -d postgres redis

# 等待数据库启动
echo "⏳ 等待数据库启动..."
sleep 10

# 启动Fluvio集群
echo "🌊 启动Fluvio集群..."
if ! fluvio cluster status > /dev/null 2>&1; then
    fluvio cluster start
fi

# 检查Fluvio集群状态
echo "✅ 检查Fluvio集群状态..."
fluvio cluster status

# 创建测试主题
echo "📊 创建测试主题..."
fluvio topic create test-topic --partitions 3 --replication-factor 1 || true
fluvio topic create user-events --partitions 2 --replication-factor 1 || true
fluvio topic create order-events --partitions 1 --replication-factor 1 || true

# 启动后端服务
echo "🦀 启动后端API服务..."
cd backend
export DATABASE_URL="postgresql://postgres:password@localhost:5432/fluviox"
export FLUVIO_CLUSTER="localhost:9003"
export RUST_LOG="info"

# 运行数据库迁移
cargo install sqlx-cli --no-default-features --features postgres || true
sqlx database create || true
sqlx migrate run || true

# 启动API网关
cargo run --bin fluviox-api-gateway &
API_PID=$!

cd ..

# 启动前端服务
echo "⚛️ 启动前端服务..."
cd frontend
npm install
npm run dev &
FRONTEND_PID=$!

cd ..

echo "🎉 FluvioX开发环境启动完成！"
echo ""
echo "📍 服务地址:"
echo "  - 前端: http://localhost:3000"
echo "  - API: http://localhost:8080"
echo "  - PostgreSQL: localhost:5432"
echo "  - Fluvio: localhost:9003"
echo ""
echo "🛑 停止服务: Ctrl+C 或运行 ./scripts/stop-dev.sh"

# 等待中断信号
trap 'echo "🛑 停止服务..."; kill $API_PID $FRONTEND_PID 2>/dev/null; fluvio cluster shutdown; docker-compose down; exit 0' INT

wait
